define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, First, $window, $timeout, $ionicSlideBoxDelegate, GoPage, $stateParams, GoDialog, Auth, GoShare, GoWapAuth, $ionicModal, $ionicPopup, $ionicSideMenuDelegate, $animateCss,$interval) {
		//画面加载
		$scope.store_id = $stateParams.store_id;
		$scope.coupon_id = $stateParams.coupon_id;
		$scope.selectIndex = 0;
		$scope.cat1_items = null;
		$scope.cat2_items = null;
		$scope.input = new Object();
		$scope.input.cat1 = '';
		$scope.input.cat1_select = {id:0,cat_name:"请选择分类"};
		$scope.input.cat2 = '';
		$scope.input.cat2_select = {id:0,cat_name:"请选择分类"};
		$scope.order = 2; //默认
		$scope.tag_id = '';
		$scope.input.brand_id = '';
		$scope.input.brand_select = {id:0,name:"请选择品牌"};
		$scope.cat = '';
		$scope.input.key = '';
		$scope.input.pricefrom = ""; //价格区间
		$scope.input.priceto = "";
		
		//判断是否ios
		$scope.isIOSApp = function() {
			if(window.cordova && window.cordova.plugins) {
				if(ionic.Platform.isIOS()) {
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		};
		
		$scope.$on('$ionicView.afterEnter', function() {
			var topH = 180;
			var bottomH = 40;
			var headerBar = document.getElementsByClassName("headerBar");//头部标题栏
			var bar_footer = document.getElementsByClassName("bar-footer");//底部导航栏
			
			if(headerBar.length>0){
				topH = headerBar[headerBar.length-1].offsetHeight;
			}
			if(bar_footer.length>0){
				bottomH = bar_footer[bar_footer.length-1].offsetHeight;
			}
			/*
			var lan = 0; //这是状态栏，只有ios的APP才有
			if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS()) { 
				lan = 20;
			}
			
			*/
			var all = $window.innerHeight;
			//店铺首页
			$scope.t_myObj1 = { //滚动条可视范围
				//"height": all - 138 - 42 - 40 - lan + "px"
				"height": all - topH - bottomH + "px"
			};
			//全部商品
			$scope.t_myObj2 = { //滚动条可视范围
				"height": all - topH - bottomH -35 + "px"
			};
			if($stateParams.index != '') {
				$scope.selectIndex = $stateParams.index;
				$ionicSlideBoxDelegate.$getByHandle('main-handle').slide($scope.selectIndex);
			}
			$scope.init_data();
		}, false);
		
		$scope.$on('$ionicView.afterLeave', function() {
			if($scope.animateTimer){
				$interval.cancel($scope.animateTimer);//取消动画定时器
			}
		}, false);
		
		//全部商品
		function initShop_goods(){
			First.shop_goods(1, $scope.store_id, $scope.input.key, $scope.cat, false, $scope.order, $scope.coupon_id, $scope.input.brand_id, $scope.tag_id,$scope.input.pricefrom,$scope.input.priceto, function(data) {
				if(data != null) {
					$scope.goods = data;
				} else{
					$scope.goods = new Object();
				}
				$scope.input.goods_nPage = 1;
			});
		}
		
		//动画。couponList为dom对象，duration滚动一次需要的时间，scrollWidth滚动的距离
		function handleCouponListSpeed(couponList,duration,scrollWidth){
			var node = angular.element(couponList);
			$scope.couponAnimate = null;
			var leftWidth = couponList.style.left;//如-171px，根据此判断是向左还是向右
			if(leftWidth==-scrollWidth+"px"){
				$scope.couponAnimate = $animateCss(node, {
					from: { 'left': -scrollWidth+"px"},//right没效果
					to: { 'left': "0px"},
					duration: duration//s数字越大，速度越慢
				});
			}else{
				$scope.couponAnimate = $animateCss(node, {
					from: { 'left': "0px"},
					to: { 'left': -scrollWidth+"px"},
					duration: duration//s数字越大，速度越慢
				});
			}
			$scope.couponAnimate.start();
		}
		
		
		//初始化。分类模板，品牌模板，标签模板，3个模板的显示样式是一样的。tag_goods,brand_goods，cat_goods
		$scope.init_data = function() {
			First.first_info($scope.store_id, function(data) {
//				console.log(data)
				if(data != null) {
					$scope.datas = data;
					$scope.go_share_wx();
					//动画
					if(data.coupons){
						$timeout(function(){//1s后滚动
							var couponList = document.getElementById("couponList");
							var scrollWidth = couponList.scrollWidth - $window.innerWidth;//元素的宽度超出屏幕最大宽度多少
							if(scrollWidth<20) return;//该值必须大于5
							var duration = scrollWidth/30;
							handleCouponListSpeed(couponList,duration,scrollWidth);
							$scope.animateTimer = $interval(function(){
								handleCouponListSpeed(couponList,duration,scrollWidth);		
							},duration*1000)
						},1000)
					}
				} else{
					$scope.datas = new Object();
				}
				$scope.input.datas_nPage = 1;
			});
			
			//全部商品
			initShop_goods();

			//客服列表
			First.getCustomerList($scope.store_id, function(data) {
				$scope.customerList = data.result;
			})
		}
		
		//滑动时候触发
		$scope.slideChanged = function(index) {
			$scope.coupon_id = '';
			$scope.tag_id = "";
			$scope.selectIndex = index;
			$scope.colseSideMenu();//关闭侧边菜单
		};
		//禁止左右滑动来切换页面1
		$scope.onTouch = function() {
			$ionicSlideBoxDelegate.$getByHandle('main-handle').enableSlide(false);
		};
		//禁止左右滑动来切换页面2
		$scope.onRelease = function() {
			$ionicSlideBoxDelegate.$getByHandle('main-handle').enableSlide(true);
		};
		
		$scope.activeSlide = function(index) {
			$scope.selectIndex = index;
			$ionicSlideBoxDelegate.$getByHandle('main-handle').slide(index);
		};
		
		//监听一级分类，获取二级分类
		$scope.$watch('input.cat1', function(newValue, oldValue) {
			if(newValue == oldValue) return;
			$scope.cat2_items = new Array();
			$scope.input.cat2 = "";
			if(newValue) {
				First.store_cat($scope.store_id, $scope.input.cat1, function(data) {
					if(data != null) {
						if(data.custom_cat.length > 0) {
							$scope.cat2_items = data.custom_cat;
						}
					}
				});
			}
		});
		
		//收藏商品
		$scope.goods_add_favorite = function(index,$event) {
			$event.stopPropagation();//阻止事件冒泡
			var goodsData = $scope.goods.goods[index];
			if(goodsData.favorite==1){
				First.del_goods_favorite(goodsData.goods_id, function(data) {
					if(data.success == true) {
						GoDialog.toast("取消收藏成功");
						goodsData.favorite = 0;
					} else{
						GoDialog.alert("提示",data.msg);
					}
				})
			}else{
				First.add_goods_favorite(goodsData.goods_id, function(data) {
					if(data.success == true) {
						GoDialog.toast("收藏成功");
						goodsData.favorite = 1;
					} else{
						GoDialog.alert("提示",data.msg);
					}
				})
			}
		}
		
		//搜索
		$scope.doSearch = function(type) {
			$scope.coupon_id = '';
			$scope.tag_id = "";
			$scope.order = 2; //默认
			if(type=="key"){//关键词搜索时，只传关键词
				$scope.cat = "";
				$scope.input.brand_id = "";
				$scope.input.brand_select = {id:0,name:"请选择品牌"};
				$scope.input.pricefrom = "";
				$scope.input.priceto = "";
			}else{
				get_cat();
			}
			$scope.selectIndex = 1;
			$ionicSlideBoxDelegate.$getByHandle('main-handle').slide(1);
			initShop_goods();
			$scope.colseSideMenu();
		}
		//获取分类id
		function get_cat() {
			if($scope.input.cat1) {
				$scope.cat = $scope.input.cat1;
			} else if($scope.input.cat2 != '') {
				$scope.cat = $scope.input.cat2;
			}else{
				$scope.cat = "";
			}
		}
		
		//排序
		$scope.orderByCount = function() {
			if($scope.order == 2) {
				$scope.order = 3;
			} else{
				$scope.order = 2;
			}
			initShop_goods();
		}
		$scope.orderByPrice = function() {
			if($scope.order == 4) {
				$scope.order = 5;
			} else{
				$scope.order = 4;
			}
			initShop_goods();
		}

		//更多 nPage,store_id,key,custom_cat,is_new,order
		/**
		 * @param {Object} type：1品牌模板  2标签模板   3分类模板
		 * @param {Object} param
		 */
		$scope.showMore = function(type, param) {
			$scope.selectIndex = 1;
			//必须让以下变量恢复到默认值
			$scope.input.key = "";
			$scope.cat = '';
			$scope.order = 2; //默认
			$scope.coupon_id = '';
			$scope.input.brand_id = '';
			$scope.input.brand_select = {id:0,name:"请选择品牌"};
			$scope.tag_id = "";
			if(type == 1) {
				$scope.input.brand_id = param;
//				console.log("品牌"+param)
			} else if(type == 2) {
				$scope.tag_id = param;
//				console.log("标签"+param)
			} else if(type == 3) {
				$scope.cat = param;
//				console.log("分类"+param)
			}
			initShop_goods();
			$ionicSlideBoxDelegate.$getByHandle('main-handle').slide(1);
		};
		
		/*************上下拉刷新*****************/
		$scope.isLoad = false;
		$scope.doRefresh = function() {
			$scope.isLoad = true;
			if($scope.selectIndex == 0) {//店铺首页
				First.get_first_list($scope.store_id,1, function(data) {
					if(data != null) {
						if(data.cat_goods) $scope.datas.cat_goods = data.cat_goods;
						if(data.brand_goods) $scope.datas.brand_goods = data.brand_goods;
						if(data.tag_goods) $scope.datas.tag_goods = data.tag_goods;
						if(data.tag_goods) $scope.datas.tag_goods = data.tag_goods;
						if(data.recommend) $scope.recommend = data.recommend;
					} else
						$scope.datas = new Object();
					$scope.input.datas_nPage = 1;
				}, function() {
					$scope.$broadcast('scroll.refreshComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				})
			} else if($scope.selectIndex == 1) {
				First.shop_goods(1, $scope.store_id, $scope.input.key, $scope.cat, false, $scope.order, $scope.coupon_id, $scope.input.brand_id, $scope.tag_id,$scope.input.pricefrom,$scope.input.priceto, function(data) {
					if(data != null)
						$scope.goods = data;
					else
						$scope.goods = new Object();
					$scope.input.goods_nPage = 1;
				}, function() {
					$scope.$broadcast('scroll.refreshComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				})
			}
		};
		
		//加载更多
		$scope.doRefreshMore = function() {
			$scope.isLoad = true;
			if($scope.selectIndex ==0){
				First.get_first_list($scope.store_id,$scope.input.datas_nPage+1, function(data) {
					if(data != null) {
						if(data.cat_goods){
							$scope.datas.cat_goods = $scope.datas.cat_goods.concat(data.cat_goods);	
						}
						if(data.brand_goods){
							$scope.datas.brand_goods= $scope.datas.brand_goods.concat(data.brand_goods);
						}
						if(data.tag_goods){
							$scope.datas.tag_goods = $scope.datas.tag_goods.concat(data.cat_goods);	
						}
						if(data.recommend){
							$scope.datas.recommend = data.recommend;
						}
					} else
						$scope.datas = new Object();
					$scope.input.datas_nPage += 1;
				}, function() {
					$scope.$broadcast('scroll.refreshComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1000);
				})
			}
			else if($scope.selectIndex == 1) {
				First.shop_goods($scope.input.goods_nPage + 1, $scope.store_id, $scope.input.key, $scope.cat, false, $scope.order, $scope.coupon_id, $scope.input.brand_id, $scope.tag_id, $scope.input.pricefrom,$scope.input.priceto,function(data) {
					if(data != null) {
						if(data.goods != undefined) {
							if($scope.goods.goods != undefined) {
								$scope.goods.goods = $scope.goods.goods.concat(data.goods);
								$scope.input.goods_nPage += 1;
							} else {
								$scope.goods = data;
							}
						}
					}
				}, function() {
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				})
			}
		};
		/*************上下拉刷新*****************/
		
		//子底部导航跳转
		$scope.onshow_subfoot = function(index, store_id) {
			if(index == 1) GoPage.go_states("shopinfo", { store_id: store_id });
			else if(index == 2) GoPage.go_states("shopmsg", { store_id: store_id });
			else GoPage.go_states("shopcustom", { store_id: store_id });
		}
		
		//页面离开，分享关闭
		$scope.$on('$ionicView.afterLeave', function() {
			$scope.closeGuidShare();
		}, false);
		
		//收藏店铺
		$scope.add_favorite = function() {
			First.add_favorite($scope.store_id, function(data) {
				if(data.success) {
					GoDialog.toast("收藏成功");
					$scope.datas.is_favorite = true;
				} else{
					GoDialog.alert("提示",data.msg);
				}
			})
		}
		
		$scope.add_friend = function() {
			First.add_friend($scope.store_id, function(data) {
				if(data.success == true) {
					GoDialog.toast("申请成功");
					$scope.datas.is_friend = 0;
				} else{
					GoDialog.alert("提示",data.msg);					
				}
			})
		}
		
		//领取优惠券
		$scope.get_coupon = function(cpns_id) {
			First.get_coupon(cpns_id, function(data) {
				if(data.success == true) {
					GoDialog.toast("优惠券领取成功");
				} else {
					GoDialog.alert("提示",data.msg);	
				}
			})
		}
		
		//清空输入
//		$scope.clear_key = function() {
//			$scope.input.key = '';
//		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share = function(index) {
			var param = new Object();
			if($scope.datas) {
				param.title = $scope.datas.store_name ? $scope.datas.store_name : undefined;
				param.desc = $scope.datas.store_type ? $scope.datas.store_type : undefined;
				param.thumb = $scope.datas.logo ? $scope.datas.logo : undefined;
				param.link = 'first/' + '/' + $scope.store_id + '/';
			}
			GoShare.do_share(param, index);
		}

		//分享（自定义每个页面的参数）
		$scope.go_share_wx = function() {
			//分享打开
			GoWapAuth.execisoff(false);
			//设置分享
			var param = new Object();
			if($scope.datas) {
				param.title = $scope.datas.store_name ? $scope.datas.store_name : undefined;
				param.desc = $scope.datas.store_type ? $scope.datas.store_type : undefined;
				param.thumb = $scope.datas.logo ? $scope.datas.logo : undefined;
				param.link = 'first/' + '/' + $scope.store_id + '/';
			}
			GoWapAuth.execshare(param);
		}

		//查看规则
		/*var rulePopup;
		$scope.showRulePopup = function(arrIndex) {
			$scope.rule = $scope.coupon[arrIndex]; //必须这样写
			rulePopup = $ionicPopup.show({
				templateUrl: 'templates/modal/showRule_coupon.html', //和couponlist.html里的“查看规则”共用一个页面
				title: "优惠券使用规则",
				scope: $scope, //绑定数据，必须写这行，
				buttons: [{
					text: "确定",
					type: "button-assertive",
					onTap: function() { // 当点击保存按钮时，执行该函数

					}
				}]
			});
		};
		//点击其他区域关闭弹出窗
		var htmlEl = angular.element(document.querySelector('html'));
		htmlEl.on('click', function(event) {
			if(event.target.nodeName === 'HTML') {
				if(rulePopup) {
					rulePopup.close();
				}
			}
		});*/

		//商品详情
		$scope.onshow_productdetail = function(goods_id) {
			if(rulePopup) {
				rulePopup.close();
			}
			$scope.go_productdetail(goods_id);
		}
		
		//返回
		$scope.back =function(){
			GoPage.go_back();
		}
		
		//切换商品的显示样式
		$scope.switchGoodsStyle = function(){
			$scope.isGoodsList = !$scope.isGoodsList;
		}
		//侧边菜单
		$scope.rightSideMenu = function() {
			$ionicSideMenuDelegate.toggleRight();
		};
		//关闭侧边菜单
		$scope.colseSideMenu = function(){
			if($ionicSideMenuDelegate.isOpenRight()){
				$ionicSideMenuDelegate.toggleRight();
			}
		}

		/***********显示《客服》**********/
		$ionicModal.fromTemplateUrl("templates/modal/customer_service.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_customer = modal;
		});
		//打开
		$scope.openModal_customer = function() {
			$scope.modal_customer.show();
		}
		//隐藏
		$scope.closeModal_customer = function() {
			$scope.modal_customer.hide();
		}
		//选择客服
		$scope.selectCustomer = function(index){
			$scope.customerList_index = index;
		}
		//联系客服
		$scope.do_tel = function() {
			$scope.closeModal_customer();
			//if(!$scope.customerList_index) return;
			var param = $scope.customerList.cusphone[$scope.customerList_index];
			if(param.type == 2) {
				$window.location.href = "tel:" + param.value;
			} else if(param.type == 1) {
				if(param.isonline == '0') {
					GoPage.go_txcall3(param.id, param.code, param.vvckey);
				} else {
					GoPage.go_txcall2($scope.store_id, $scope.store_id, param.id, param.code, param.vvckey);
				}
			}
		}
		/***********显示《客服》**********/
		
		/***************分享**************/
		$ionicModal.fromTemplateUrl("templates/modal/keyshare_modal.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_share = modal;
		});
		//打开
		$scope.openModal_share = function() {
			if($scope.openGuidShare()) {
				$scope.modal_share.show();
			}
		}
		//隐藏
		$scope.closeModal_share = function() {
			$scope.modal_share.hide();
		}
		/***************分享**************/
		
		/***************关于我们**************/
		$ionicModal.fromTemplateUrl("templates/modal/aboutus_first.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_aboutus = modal;
		});
		//打开
		$scope.openModal_aboutus = function() {
			$scope.modal_aboutus.show();
		}
		//隐藏
		$scope.closeModal_aboutus = function() {
			$scope.modal_aboutus.hide();
		}
		/***************关于我们**************/
		
		$scope.doSelectBrand = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择品牌",$scope.datas.brand,$scope.input.brand_select,function(data){
				$scope.input.brand_id = data.id;
				$scope.input.brand_select = data;
			});
		}
		$scope.doSelectCat1 = function(){
			var list = new Array();
			$scope.datas.custom_cat.forEach(obj => {
				if(obj.disabled == false){
					if(obj.id == undefined)
					obj.id = obj.custom_cat_id;
					list.push(obj);
				}
			});
			//id是值 name是显示
			GoDialog.showSelect("大分类",list,$scope.input.cat1_select,function(data){
				$scope.input.cat1 = data.custom_cat_id;
				$scope.input.cat1_select = data;
				$scope.input.cat2_select = {id:0,cat_name:"请选择分类"};
			});
		}
		$scope.doSelectCat2 = function(){
			var list = new Array();
			$scope.cat2_items.forEach(obj => {
				if(obj.disabled == false){
					if(obj.id == undefined)
					obj.id = obj.custom_cat_id;
					list.push(obj);
				}
			});
			//id是值 name是显示
			GoDialog.showSelect("中分类",list,$scope.input.cat2_select,function(data){
				$scope.input.cat2 = data.custom_cat_id;
				$scope.input.cat2_select = data;
			});
		}

		//跳转到商品详情
		$scope.go_productdetail = function(goods_id) {
			GoPage.go_states("productdetail", { "goods_id": goods_id, "type": 'goods' });
		}
		
	}

	controller.$inject = ['$scope', 'First', '$window', '$timeout', '$ionicSlideBoxDelegate', 'GoPage', '$stateParams', 'GoDialog', 'Auth', 'GoShare', 'GoWapAuth', '$ionicModal', '$ionicPopup','$ionicSideMenuDelegate','$animateCss','$interval'];

	return app.registerController("firstctrl", controller);
});